/*输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。*/
var spiralOrder = function (matrix) {
    if(matrix.length===0)return matrix

    let row = matrix.length;    //有多少行
    let col = matrix[0].length  //有多少列

    let i = 0, j = 0;
    /*这里要使用.map()*/
    let arr = Array(row).fill().map(() => Array(col).fill(0));
    arr[0][0] = 1;
    let ans = [matrix[0][0]];
    let out = true;
    let check = [rightable, downable, leftable, upable]

    while (out) {
        out = false
        for (let m = 0; m < 4; m++) {
            //这里要注意有小括号
            if (check[0]()) {
                out = true;
                break;
            } else {
                check.push(check.shift())
            }
        }

    }

    //这里不能写rightable(i,j)，不然i,j就作为参数了。基本类型做参数，不改变原来的值
    function rightable() {
        if (j + 1 < col && arr[i][j + 1] === 0) {
            ans.push(matrix[i][++j]);
            arr[i][j] = 1;
            return true;
        } else return false;
    }

    function downable() {
        if (i + 1 < row && arr[i + 1][j] === 0) {
            ans.push(matrix[++i][j]);
            arr[i][j] = 1;
            return true
        } else return false;
    }

    function leftable() {
        if (j - 1 >= 0 && arr[i][j - 1] === 0) {
            ans.push(matrix[i][--j]);
            arr[i][j] = 1;
            return true
        } else return false;
    }

    function upable() {
        if (i - 1 >= 0 && arr[i - 1][j] === 0) {
            ans.push(matrix[--i][j]);
            arr[i][j] = 1;
            return true
        } else return false
    }
    return ans;
};


let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(spiralOrder(matrix))


/*fill()方法的用法*/
var fruits = ["Banana", "Orange", "Apple", "Mango","Pear"];
fruits.fill("Runoob", 2, 4);
console.log(fruits)

